package com.goldmantis.alitrip.common.exception;

import com.goldmantis.alitrip.common.ReturnMessage;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:Shmily
 * @Description:
 * @Date:Create in 15:09 2018/2/11
 */
@RestControllerAdvice
public class ExceptionController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionController.class);

    /**
     * 捕捉shiro的异常
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ReturnMessage handle401(ShiroException ex) {
        LOGGER.error(ex.getMessage(),ex);
        return ReturnMessage.failure(ex);
    }

    /**
     * 捕捉UnauthorizedException
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ReturnMessage handle401(UnauthorizedException ex) {
        LOGGER.error(ex.getMessage(),ex);
        return ReturnMessage.failure(ex);
    }


    /**
     * 捕捉其他所有异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ReturnMessage globalException(HttpServletRequest request, Throwable ex) {
        LOGGER.error(ex.getMessage(),ex);
        return ReturnMessage.failure(new Exception(ex.getMessage()));
    }

    /**
     * 捕捉其他运行时异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ReturnMessage globalRuntimeException(HttpServletRequest request, Throwable ex) {
        LOGGER.error(ex.getMessage(),ex);
        return ReturnMessage.failure(new Exception(ex.getMessage()));
    }

    /**
     * 参数验证异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ReturnMessage handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        LOGGER.error(ex.getMessage(),ex);
        List<FieldError> allErrors = ex.getBindingResult().getFieldErrors();
        Map<String,Object> map=new HashMap<>();
        for(FieldError item :allErrors){
            map.put(item.getField(),item.getDefaultMessage());
        }
        return ReturnMessage.failure(ex).add("fieldsError",map);
    }
}
